package com.topvision.controller.ar;

import com.alibaba.fastjson.JSONObject;
import com.topvision.controller.AbstractController;
import com.topvision.model.ar.OffFace;
import com.topvision.model.shrio.SysUser;
import com.topvision.service.ar.OffFaceService;
import com.topvision.service.shrio.SysUserService;
import com.topvision.util.FaceApiUtil;
import com.topvision.util.PageUtils;
import com.topvision.util.Query;
import com.topvision.util.R;
import com.topvision.utils.ShiroUtils;
import com.topvision.utils.UnZipFile;
import com.topvision.utils.UpdateFileNameUtils;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.easy.excel.ExcelContext;
import org.easy.excel.result.ExcelImportResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * 离线人脸数据
 *
 * @author shengwm
 * @email 179653076@qq.com
 * @date 2018-03-12 13:03:12
 */
@RestController
@RequestMapping("ar/offface")
public class OffFaceController extends AbstractController {
    @Autowired
    private OffFaceService offFaceService;
    @Autowired
    private SysUserService sysUserService;


    @Value("#{APP_PROP['off.face.imgurl']}")
    private String imgurl;


    @Value("#{APP_PROP['off.face.imglocation']}")
    private String imglocation;

    private static ExcelContext context = new ExcelContext("excel-config.xml");

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("ar/offface:list")
    public R list(@RequestParam Map<String, Object> params) {


        Long userId = ShiroUtils.getUserId();
        if (userId != null && userId != 1L) {
            SysUser sysUser = sysUserService.queryObject(userId);
            String companycode = sysUser.getCompanycode();
            if (companycode != null) {
                params.put("companycode", companycode);
            }

        }

        //查询列表数据
        Query query = new Query(params);

        List<OffFace> offFaceList = offFaceService.queryList(query);
        int total = offFaceService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(offFaceList, total, query.getLimit(), query.getPage());

        return R.success().put("page", pageUtil);
    }

    @RequestMapping("/findListByParam")
    @RequiresPermissions("ar/offface:list")
    public R findListByParam(@RequestParam Map<String, Object> params) {

        List<OffFace> offFaceList = offFaceService.queryByParam(params);

        return R.success().put("offFaceList", offFaceList);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("ar/offface:info")
    public R info(@PathVariable("id") Long id) {
        OffFace offFace = offFaceService.queryObject(id);
        return R.success().put("offFace", offFace);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("ar/offface:save")
    public R save(HttpServletRequest request) throws Exception {
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        InputStream inputStream = null;
        // 文件类型
        MultipartHttpServletRequest multiRequest = null;
        String originalFilename = null;


        LocalDate date = LocalDate.now();
        Long id = ShiroUtils.getUserId();
        SysUser sysUser = sysUserService.queryObject(id);
        String companycode = sysUser.getCompanycode();


        if (request instanceof MultipartHttpServletRequest) {
            multiRequest = (MultipartHttpServletRequest) request;
            try {
                inputStream = multiRequest.getFile("face").getInputStream();
                originalFilename = multiRequest.getFile("face").getOriginalFilename();
                String path = imglocation + date.toString() + "/" + companycode + "/" + originalFilename;
                File file = new File(path);
                FileUtils.copyInputStreamToFile(inputStream, file);
                Map<String, Object> map = new HashMap<>();
                String code = file.getName().split("\\.")[0];
                map.put("dbname", companycode);
                map.put("filetag", code);
                map.put("file", file);
                JSONObject json = FaceApiUtil.addSmartFace(map);
                if (json.get("value").equals("SUCCESS")) {
                    String url = imgurl + date.toString() + "/" + sysUser.getCompanycode() + "/" + originalFilename;
                    OffFace offFace = new OffFace();
                    offFace.setCompanycode(companycode);
                    offFace.setUrl(url);
                    offFace.setType(multiRequest.getParameter("type"));
                    offFace.setTruename(multiRequest.getParameter("name"));
                    offFace.setFacenumber(multiRequest.getParameter("idcard"));
                    offFace.setCreateTime(new Date());
                    offFace.setCreateUserId(sysUser.getUserId());
                    offFaceService.save(offFace);
                    return R.success(offFace);
                } else {
                    return R.error(json.toJSONString());
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            System.out.println(multiRequest.getParameter("type"));
        }

        return R.success();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("ar/offface:update")
    public R update(@RequestBody OffFace offFace) {
        offFaceService.update(offFace);
        return R.success();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("ar/offface:delete")
    public R delete(@RequestBody Long[] ids) {
        List<OffFace> offFaces = offFaceService.queryObjects(ids);
        List<String> strings = new ArrayList<>();
        if (offFaces.size() > 0) {
            for (OffFace offface : offFaces) {
                if (offface.getUrl() != null) {
                    strings.add(offface.getUrl());
                }
            }
        }
        offFaceService.deleteBatch(ids);
        for (String str : strings) {
            String[] codes = str.split("/");
            String dir = imglocation  + codes[5] + "/" + codes[6] + "/" + codes[7];
            logger.info(dir);
            try {
                FileUtils.forceDelete(new File(dir));
            } catch (IOException e) {
            }

        }
        return R.success();
    }


    /**
     * 导入excel
     */
    @RequestMapping("/importexcel")
    @RequiresPermissions("ar/offface:delete")
    public R importexcel(HttpServletRequest request) throws Exception {
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        InputStream inputStream = null;
        // 文件类型
        MultipartHttpServletRequest multiRequest = null;
        if (request instanceof MultipartHttpServletRequest) {
            multiRequest = (MultipartHttpServletRequest) request;
            try {
                inputStream = multiRequest.getFile("inputexcel").getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // String period = request.getParameter("period");
        //  String imgurl = "http://172.16.10.10:36319/facedata/";
        ExcelImportResult result = context.readExcel("offface", 0, inputStream);
        List<OffFace> offFaces = result.getListBean();
        Long id = ShiroUtils.getUserId();
        SysUser sysUser = sysUserService.queryObject(id);
        LocalDate date = LocalDate.now();
        //String filePar = "F:\\temp\\" + date.toString();// 文件夹路径
        String filePar = imglocation + date.toString();// 文件夹路径
        String url = imgurl + date.toString() + "/" + sysUser.getCompanycode() + "/";
        logger.info(url);
        File myPath = new File(filePar);
        if (!myPath.exists()) {//若此目录不存在，则创建之
            myPath.mkdir();
            System.out.println("创建文件夹路径为：" + filePar);
        }
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDate = LocalDateTime.now();
        ZonedDateTime zdt = localDate.atZone(zoneId);

      /*  LocalDateTime delDatez = localDate.plusDays(Integer.valueOf(period));
        ZonedDateTime delZ = delDatez.atZone(zoneId);*/

       /* Date delDate = Date.from(delZ.toInstant());
        Date createDate = Date.from(zdt.toInstant());*/


        Map<String, OffFace> map = new HashMap<>();
        for (OffFace offface : offFaces) {
            if (map.containsKey(offface.getFacenumber())) {
                map.get(offface.getFacenumber()).setType(map.get(offface.getFacenumber()).getType() + "-" + offface.getType());
            } else {
                offface.setCreateUserId(id);
                offface.setCreateTime(new Date());
                offface.setUrl(url + offface.getFacenumber() + ".jpg");
                offface.setCompanycode(sysUser.getCompanycode());
                offface.setCreateUserId(sysUser.getUserId());
                // offface.setDelTime(delDate);
                map.put(offface.getFacenumber(), offface);
            }
        }
        // Collection<OffFace> values = map.values();
        List<OffFace> list = new ArrayList<>(map.values());
        offFaceService.insertBatch(list);
        //关闭输入流
        inputStream.close();

        return R.success();
    }


    /**
     * 导入excel
     */
    @RequestMapping("/uploadzip")
    @RequiresPermissions("ar/offface:delete")
    public R uploadzip(HttpServletRequest request) throws Exception {
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        InputStream inputStream = null;
        // 文件类型
        MultipartHttpServletRequest multiRequest = null;
        List<String> list = new ArrayList<>();
        if (request instanceof MultipartHttpServletRequest) {
            multiRequest = (MultipartHttpServletRequest) request;
            File file = multipartToFile(multiRequest.getFile("uploadzip"));
            // UnZipFile.decompress(file);
            LocalDate date = LocalDate.now();
            Long id = ShiroUtils.getUserId();
            SysUser sysUser = sysUserService.queryObject(id);
            String companycode = sysUser.getCompanycode();
            String path = imglocation + date.toString() + "/" + companycode;
            UnZipFile.uzip(file, path);
            //当前公司目录
            File files = new File(path);
            File[] filearr = files.listFiles();
            String db = companycode;
            String code = null;
            Map<String, Object> parammap = new HashMap<>();
            if (filearr != null && filearr.length > 0) {
                for (File f : filearr) {
                    code = f.getName().split("\\.")[0];
                    parammap.put("dbname", db);
                    parammap.put("filetag", code);
                    parammap.put("file", f);
                    JSONObject json = FaceApiUtil.addSmartFace(parammap);
                    if (json != null) {
                        list.add(json.toJSONString());
                    }

                }
            }

        }
        //String entryFile = "D:\\dev\\2018-3-15.zip";
        return R.success().put("result", list);
    }


    /**
     * MultipartFile 转换成File
     *
     * @param multfile 原文件类型
     * @return File
     * @throws IOException
     */
    public File multipartToFile(MultipartFile multfile) throws IOException {
        CommonsMultipartFile cf = (CommonsMultipartFile) multfile;
        //这个myfile是MultipartFile的
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        File file = fi.getStoreLocation();
        String name = FilenameUtils.getExtension(fi.getName());
        //手动创建临时文件
        if (file.length() / 1024 < 3 * 1024) {
            File tmpFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") +
                    file.getName().replace("tmp", name));
            multfile.transferTo(tmpFile);
            return tmpFile;
        }
        return file;
    }
}
